package em.job;

import base.jfinal.anatation.TimerBind;
import base.util.PropertiesContent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 处理与服务器上保持长时间的连接
 * 每隔1分钟执行一次心跳包
 */
@TimerBind(ClassSpace = "em.job.ConnServer",Cron="0 */1 * ? * *",Enable=true)
public class ConnServer implements Job {
    private static ConnServer connServer;
    public Socket client = null;
    private boolean isOk=false;
    public BufferedReader reader = null;
    public BufferedOutputStream writer = null;
    private Log logger = LogFactory.getLog(ConnServer.class);

    public synchronized static ConnServer getInstance(){
        if (connServer==null) {
            connServer=new ConnServer();
            connServer.createClient();
        }
        return connServer;
    }

    public boolean isConn(){
        return isOk;
    }
    public boolean createClient(){
        try {
            client = new Socket();
            client.connect(new InetSocketAddress(PropertiesContent.get("term_server_address"), PropertiesContent.getToInteger("term_server_prot", 8890)));
            client.setKeepAlive(true);
            client.setSoTimeout(0);
            reader = new BufferedReader(new InputStreamReader(
                    client.getInputStream()));
            writer = new BufferedOutputStream(client.getOutputStream());
            isOk=true;
            writer.write("{}".getBytes());
            logger.error("创建连接成功");
        } catch (IOException e) {
            logger.error("创建连接失败,失败信息："+e.getMessage());
            isOk=false;
        }
        return isOk;
    }

    /**
     * 重置连接
     */
    public void resetConn(){
        int iReset= PropertiesContent.getToInteger("term_server_resetConn",3);
        for (int i=0;i<iReset;i++)
            if(createClient()) break;
    }
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try{
            ConnServer.getInstance().writer.write("{}".getBytes());
            ConnServer.getInstance().writer.flush();
        }catch (Exception ex){
            logger.error("**********连接失败,等待重连**********");
            ConnServer.getInstance().isOk=false;
            ConnServer.getInstance().resetConn();
        }
    }

    /**
     * 发送数据
     * @param command
     */
    public synchronized boolean sendData(String command){
        try {
            if(connServer.isConn()) {
                ConnServer.getInstance().writer.write(command.toString().getBytes());
                ConnServer.getInstance().writer.flush();
                return true;
            }
        } catch (IOException e) {
            logger.debug("客户端:发送指令失败,等待重连.失败消息："+e.getMessage()+"，指令消息：" +command);
        }
        return false;
    }

    /**
     * 发送数据
     * @param command
     */
    public synchronized boolean sendData(String command, byte[] bytes,int start, int end){
        try {
            if (connServer.isConn()) {
                ConnServer.getInstance().writer.write(command.toString().getBytes());
                ConnServer.getInstance().writer.write(bytes, start, end);
                ConnServer.getInstance().writer.flush();
                //logger.debug("客户端:发送指令" + command);
                return true;
            }
        } catch (IOException ex) {
            logger.debug("客户端:发送指令失败,等待重连.失败消息："+ex.getMessage());
        }
        return false;
    }
}
